package model

import (
	"awesomeProject2/global"
	"gorm.io/gorm"
	"strconv"
)

type Patent struct {
	gorm.Model
	PatentCategory string `json:"patentCategory"  gorm:"type:varchar(255);"`
	PatentFile     string `json:"patentFile" gorm:"type:varchar(255);"`
	PatentName     string `json:"patentName" gorm:"type:varchar(255);"`
	PatentNumber   string `json:"patentNumber"  gorm:"type:varchar(255);"`
	PatentRanking  int    `json:"patentRanking"  gorm:"type:int"`
	//PatentScore    *int   `json:"patentScore" form:"patentScore" gorm:"column:patentScore;comment:;type:int"`
	UserId     uint `json:"userid"  gorm:"type:bigint"`
	Is_Visible bool `json:"is_visible"  gorm:"type:tinyint"`
	Year       int  `json:"year" gorm:"type:int"`
}

func GetPatent(id uint) (err error, patent Patent) {
	err = global.GVA_DB.Where("id = ?", id).First(&patent).Error
	return err, patent
}

func CreatePatent(patent Patent) (err error) {
	err = global.GVA_DB.Create(&patent).Error
	return err
}
func DeletePatent(id int) (err error) {
	err = global.GVA_DB.Where("id = ?", id).Delete(&Patent{}).Error
	return err
}

func UpdatePatent(data Patent) (err error) {
	err = global.GVA_DB.Updates(data).Where("id = ?", data.ID).Error
	return err
}

func GetPatents(userid uint, pageSize int, pageNum int) (err error, list interface{}, total int) {
	var patents []Patent
	var tt int64
	err = global.GVA_DB.Limit(pageSize).Offset((pageNum-1)*pageSize).Where("user_id = ?", userid).Find(&patents).Count(&tt).Error

	tmp := strconv.FormatInt(tt, 10)
	total, _ = strconv.Atoi(tmp)
	return err, patents, total
}

func ChangePatentVisiblity(id uint) (err error) {
	var data Patent
	err = global.GVA_DB.Where("id = ?", id).First(&data).Error
	data.Is_Visible = !data.Is_Visible
	global.GVA_DB.Updates(data)
	return err
}
func GetAllPatens(id uint, year int) (error, interface{}, int64) {
	var data []Patent
	var tt int64
	err := global.GVA_DB.Where("user_id = ? AND year = ?", id, year).Find(&data).Count(&tt).Error
	return err, data, tt
}

func GetAllPatens3(id uint) (error, interface{}, int64) {
	var data []Patent
	var tt int64
	err := global.GVA_DB.Where("user_id = ? ", id).Find(&data).Count(&tt).Error
	return err, data, tt
}

//统计总数目
func GetAllpt(year int) (error, int64) {
	var tt int64
	err := global.GVA_DB.Model(&Patent{}).Where("year = ?", year).Count(&tt).Error
	return err, tt
}
